<template>
  <div class="add-patient-page">
    <div v-if="patientList.length > 0">
      <van-cell-group>
        <van-cell
          v-for="(patient, index) in patientList"
          :key="index"
          class="patient-cell"
        >
          <template #title>
            <div class="patient-info">
              <div class="name-phone">
                <span class="name">{{ patient.patientName }}</span>
                <span class="phone">{{ patient.phone }}</span>
              </div>
              <div class="id-info">
                <div class="patient-details">
                  <span class="gender">性别：{{ patient.gender }}</span>
                  <span class="age">年龄：{{ patient.age }}</span>
                </div>
                <span class="id-number">{{ patient.identity }}</span>
              </div>
            </div>
          </template>
          <template #right-icon>
            <van-button
              type="danger"
              size="small"
              @click="deletePatient(index)"
            >
              删除
            </van-button>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    <div v-else>
      <div class="empty-tip">暂无就诊人信息</div>
    </div>
    <div class="fixed-bottom">
      <van-button
        type="primary"
        block
        round
        class="add-patient-btn"
        @click="openAddPatientPopup"
      >
        添加就诊人
      </van-button>
    </div>
    <!-- 添加就诊人弹框 -->
    <van-popup
      v-model:show="showAddPatientPopup"
      position="bottom"
      class="add-patient-popup"
    >
      <van-cell-group>
        <van-field
          v-model="newPatient.name"
          label="姓名"
          placeholder="请输入姓名"
        />
        <van-field
          v-model="newPatient.phone"
          label="手机号"
          placeholder="请输入手机号"
          type="number"
          :error-message="phoneErrorMessage"
          @blur="validatePhone" 
        />
        <van-field
          v-model="newPatient.idCardNumber"
          label="身份证号码"
          placeholder="请输入身份证号码"
          :error-message="idCardNumberErrorMessage"
          @blur="validateIdCard" 
          @input="parseIdCard" 
        />
        <van-field
          v-model="newPatient.gender"
          label="性别"
          placeholder="请选择性别"
          readonly
          clickable
          @click="selectGender"
        />
        <van-popup v-model:show="showGenderPopup" position="bottom">
          <van-radio-group v-model="newPatient.gender">
            <van-radio name="男">男</van-radio>
            <van-radio name="女">女</van-radio>
          </van-radio-group>
          <van-button block @click="showGenderPopup = false">确认</van-button>
        </van-popup>
        <van-field
          v-model="newPatient.age"
          label="年龄"
          placeholder="请输入年龄"
          type="number"
          :error-message="ageErrorMessage"
        />
      </van-cell-group>
      <div class="popup-btns">
        <van-button
          type="primary"
          block
          @click="addPatient"
        >
          确认添加
        </van-button>
        <van-button
          type="default"
          block
          @click="closeAddPatientPopup"
        >
          取消
        </van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { CellGroup, Cell, Button, Field, Popup, RadioGroup, Radio, showToast } from 'vant';
import { useRouter } from 'vue-router';
import { addPatientInfoAPI, getPatientInfoAPI } from '../../api/user/user.js';
import { useUserStore } from '../../stores/user.js';

const router = useRouter();
const userStore = useUserStore();

const goBack = () => {
  router.back();
};

// 就诊人列表
const patientList = ref([]);

// 获取就诊人列表
const fetchPatientList = async () => {
  try {
    const res = await getPatientInfoAPI();
    if (res.success) {
      patientList.value = res.data;
    }
  } catch (error) {
    showToast('获取就诊人列表失败');
  }
};

// 组件挂载时获取就诊人列表
onMounted(() => {
  fetchPatientList();
});

// 添加就诊人弹框相关
const showAddPatientPopup = ref(false);
const newPatient = ref({
  name: '',
  phone: '',
  idCardNumber: '',
  gender: '',
  age: ''
});
const phoneErrorMessage = ref('');
const idCardNumberErrorMessage = ref('');
const ageErrorMessage = ref('');
const showGenderPopup = ref(false); // 确保 showGenderPopup 已定义

const openAddPatientPopup = () => {
  showAddPatientPopup.value = true;
  phoneErrorMessage.value = '';
  idCardNumberErrorMessage.value = '';
  ageErrorMessage.value = '';
};

const closeAddPatientPopup = () => {
  showAddPatientPopup.value = false;
  newPatient.value = {
    name: '',
    phone: '',
    idCardNumber: '',
    gender: '',
    age: ''
  };
  phoneErrorMessage.value = '';
  idCardNumberErrorMessage.value = '';
  ageErrorMessage.value = '';
};

// 完善选择性别方法
const selectGender = () => {
  showGenderPopup.value = true;
};

// 实时验证手机号
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(newPatient.value.phone)) {
    phoneErrorMessage.value = '请输入有效的手机号码';
  } else {
    phoneErrorMessage.value = '';
  }
};

// 实时验证身份证号码
const validateIdCard = () => {
  const idCardNumberRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (!idCardNumberRegex.test(newPatient.value.idCardNumber)) {
    idCardNumberErrorMessage.value = '请输入有效的身份证号码';
  } else {
    idCardNumberErrorMessage.value = '';
    // 验证通过后解析身份证信息
    parseIdCard(newPatient.value.idCardNumber);
  }
};

// 解析身份证号码
const parseIdCard = (idCard) => {
  if (!idCard) return;
  
  // 获取出生日期
  let birth = '';
  if (idCard.length === 18) {
    birth = idCard.substring(6, 14);
  } else if (idCard.length === 15) {
    birth = '19' + idCard.substring(6, 12);
  }
  
  // 计算年龄
  if (birth) {
    const year = parseInt(birth.substring(0, 4));
    const month = parseInt(birth.substring(4, 6));
    const day = parseInt(birth.substring(6, 8));
    
    const today = new Date();
    const birthDate = new Date(year, month - 1, day);
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    
    newPatient.value.age = age.toString();
  }
  
  // 获取性别
  if (idCard.length === 18) {
    const sexNum = parseInt(idCard.substring(16, 17));
    newPatient.value.gender = sexNum % 2 === 0 ? '女' : '男';
  } else if (idCard.length === 15) {
    const sexNum = parseInt(idCard.substring(14, 15));
    newPatient.value.gender = sexNum % 2 === 0 ? '女' : '男';
  }
};

// 添加就诊人方法
const addPatient = async () => {
  if (!newPatient.value.name) {
    showToast('请输入姓名');
    return;
  }
  if (!newPatient.value.phone || phoneErrorMessage.value) {
    showToast('请输入正确的手机号');
    return;
  }
  if (!newPatient.value.idCardNumber || idCardNumberErrorMessage.value) {
    showToast('请输入正确的身份证号码');
    return;
  }
  if (!newPatient.value.gender) {
    showToast('请选择性别');
    return;
  }
  if (!newPatient.value.age) {
    showToast('请输入年龄');
    return;
  }

  const params = {
    patientName: newPatient.value.name,
    phone: newPatient.value.phone,
    identity: newPatient.value.idCardNumber,
    gender: newPatient.value.gender,
    age: newPatient.value.age,
  }

  try {
    const res = await addPatientInfoAPI(params);
    if (res.success) {
      patientList.value.push(res.data);
      showToast('添加成功');
      closeAddPatientPopup();
    }
  } catch (error) {
    showToast('添加失败，请重试');
  }
};

// 删除就诊人
const deletePatient = (index) => {
  patientList.value.splice(index, 1);
};
</script>

<style scoped>
.add-patient-page {
  padding: 16px;
}

.empty-tip {
  text-align: center;
  color: #999;
  margin-top: 20px;
}

.add-patient-btn {
  margin-top: 20px;
}

.add-patient-popup {
  padding: 16px;
}

.popup-btns {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.fixed-bottom {
  position: fixed; /* 固定位置 */
  bottom: 0;       /* 距离底部 0 */
  left: 25%;         /* 距离左侧 0 */
  width: 50%;     /* 宽度占满屏幕 */
  padding: 10px 0; /* 内边距，调整按钮与边缘的距离 */
  z-index: 100;    /* 确保覆盖其他内容 */
}

.patient-cell {
  padding: 10px;
}

.patient-info {
  display: flex;
  flex-direction: column;
  padding-right: 10%;
}

.name-phone {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.name {
  font-size: 16px;
  font-weight: bold;
}

.phone {
  font-size: 14px;
  color: #666;
}

.id-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-details {
  display: flex;
  gap: 10px;
  color: #666;
  font-size: 14px;
}

.gender, .age {
  color: #666;
}

.id-type {
  font-size: 14px;
  color: #999;
}

.id-number {
  font-size: 14px;
  color: #666;
}
</style>